package com.sz.admin.web.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.mybatisflex.core.query.QueryWrapper;
import com.sz.admin.dtutransportinfo.pojo.dto.DtuTransportInfoListDTO;
import com.sz.admin.dtutransportinfo.pojo.vo.DtuTransportInfoVO;
import com.sz.admin.dtutransportinfo.service.DtuTransportInfoService;
import com.sz.admin.system.service.SysDeptDirectService;
import com.sz.admin.system.service.SysDeptLeaderService;
import com.sz.core.common.constant.GlobalConstant;
import com.sz.core.common.entity.ApiResult;
import com.sz.core.common.entity.LoginUser;
import com.sz.core.common.entity.PageResult;
import com.sz.core.util.PageUtils;
import com.sz.netty.entity.DtuFtpInfo;
import com.sz.netty.service.DtuFtpInfoService;
import com.sz.security.config.LoginType;
import com.sz.security.core.util.LoginUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.column;

/**
 * 工作详情控制器
 */
@Tag(name = "工作详情")
@RestController
@RequestMapping("/web/work-detail")
@RequiredArgsConstructor
public class WorkDetailController {

    private final SysDeptLeaderService sysDeptLeaderService;
    private final SysDeptDirectService sysDeptDirectService; // Use the new direct service
    private final DtuFtpInfoService dtuFtpInfoService;
    private final DtuTransportInfoService dtuTransportInfoService;

    /**
     * 获取当前登录用户所属部门和所有下级部门的所有设备deviceId列表
     *
     * @return 设备deviceId列表
     */
    @Operation(summary = "获取当前用户部门及下级部门的设备列表")
    @SaCheckLogin(type = LoginType.WEB)
    @GetMapping("/device-ids")
    public ApiResult<List<String>> getDeviceIdsByDept() {
        // 1. 获取当前登录用户
        LoginUser loginUser = LoginUtils.getLoginUserByType(LoginType.WEB);
        if (loginUser == null) {
            return ApiResult.success(new ArrayList<>());
        }

        // 2. 获取用户所属部门（领导身份）
        List<Long> leaderDepts = sysDeptLeaderService.list()
                .stream()
                .filter(leader -> leader.getLeaderId().equals(loginUser.getUserInfo().getId()))
                .map(leader -> leader.getDeptId())
                .toList();

        if (leaderDepts.isEmpty()) {
            return ApiResult.success(new ArrayList<>());
        }

        // 3. 获取部门及其所有下级部门（使用新的直接查询方法）
        List<Long> allDepts = new ArrayList<>(leaderDepts);
        List<Long> descendants = sysDeptDirectService.getSubordinateDeptIds(leaderDepts);
        if (descendants != null && !descendants.isEmpty()) {
            allDepts.addAll(descendants);
        }

        // 4. 查询这些部门下的所有设备
        List<DtuFtpInfo> devices = dtuFtpInfoService.list(
                QueryWrapper.create()
                        .from(DtuFtpInfo.class)
                        .where(DtuFtpInfo::getDeptId).in(allDepts)
        );

        // 5. 提取deviceId列表
        List<String> deviceIds = devices.stream()
                .map(DtuFtpInfo::getDeviceId)
                .toList();

        return ApiResult.success(deviceIds);
    }

    /**
     * 分页查询运输数据列表
     *
     * @param dto 查询参数
     * @return 运输数据分页列表
     */
    @Operation(summary = "分页查询运输数据")
    @SaCheckLogin(type = LoginType.WEB)
    @GetMapping("/transport-page")
    public ApiResult<PageResult<DtuTransportInfoVO>> pageTransportData(DtuTransportInfoListDTO dto) {
        // 1. 获取当前登录用户
        LoginUser loginUser = LoginUtils.getLoginUserByType(LoginType.WEB);
        if (loginUser == null) {
            return ApiResult.success(PageUtils.getPageResult(new ArrayList<>()));
        }

        // 2. 获取用户所属部门（领导身份）
        List<Long> leaderDepts = sysDeptLeaderService.list()
                .stream()
                .filter(leader -> leader.getLeaderId().equals(loginUser.getUserInfo().getId()))
                .map(leader -> leader.getDeptId())
                .toList();

        if (leaderDepts.isEmpty()) {
            return ApiResult.success(PageUtils.getPageResult(new ArrayList<>()));
        }

        // 3. 获取部门及其所有下级部门（使用新的直接查询方法）
        List<Long> allDepts = new ArrayList<>(leaderDepts);
        List<Long> descendants = sysDeptDirectService.getSubordinateDeptIds(leaderDepts);
        if (descendants != null && !descendants.isEmpty()) {
            allDepts.addAll(descendants);
        }

        // 4. 查询这些部门下的所有设备deviceId
        List<DtuFtpInfo> devices = dtuFtpInfoService.list(
                QueryWrapper.create()
                        .from(DtuFtpInfo.class)
                        .where(DtuFtpInfo::getDeptId).in(allDepts)
        );

        List<String> deviceIds = devices.stream()
                .map(DtuFtpInfo::getDeviceId)
                .toList();

        if (deviceIds.isEmpty()) {
            return ApiResult.success(PageUtils.getPageResult(new ArrayList<>()));
        }

        // 5. 查询运输数据，只查询当前用户部门及下级部门的设备数据
        QueryWrapper transportQuery = QueryWrapper.create()
                .from(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo.class)
                .where(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getDtuNumber).in(deviceIds)
                .orderBy(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getId, false); // Order by ID descending

        // 复制原始查询条件
        if (dto.getDtuNumber() != null && !dto.getDtuNumber().isEmpty()) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getDtuNumber).eq(dto.getDtuNumber());
        }
        if (dto.getUserId() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getUserId).eq(dto.getUserId());
        }
        if (dto.getStartTimeStart() != null && dto.getStartTimeEnd() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getStartTime).between(dto.getStartTimeStart(), dto.getStartTimeEnd());
        } else if (dto.getStartTimeStart() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getStartTime).ge(dto.getStartTimeStart());
        } else if (dto.getStartTimeEnd() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getStartTime).le(dto.getStartTimeEnd());
        }
        if (dto.getEndTimeStart() != null && dto.getEndTimeEnd() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getEndTime).between(dto.getEndTimeStart(), dto.getEndTimeEnd());
        } else if (dto.getEndTimeStart() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getEndTime).ge(dto.getEndTimeStart());
        } else if (dto.getEndTimeEnd() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getEndTime).le(dto.getEndTimeEnd());
        }
        
        // Handle startDate and endDate parameters to filter by create_time
        if (dto.getStartDate() != null && dto.getEndDate() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getCreateTime).between(dto.getStartDate(), dto.getEndDate());
        } else if (dto.getStartDate() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getCreateTime).ge(dto.getStartDate());
        } else if (dto.getEndDate() != null) {
            transportQuery.and(com.sz.admin.dtutransportinfo.pojo.po.DtuTransportInfo::getCreateTime).le(dto.getEndDate());
        }

        // 执行分页查询
        com.mybatisflex.core.paginate.Page<DtuTransportInfoVO> page = 
            dtuTransportInfoService.pageAs(
                PageUtils.getPage(dto), 
                transportQuery, 
                DtuTransportInfoVO.class
            );

        return ApiResult.success(PageUtils.getPageResult(page));
    }
}